<template>
  <h2>通知公告分类管理页面</h2>

  <el-button type="primary" @click="dialogFormVisible = true">添加分类</el-button>
  <!-- 添加通知公告的表单-弹框 -->
  <el-dialog v-model="dialogFormVisible" title="添加通知公告分类" width="500">
    <el-form :model="addNoticeform">
      <el-form-item label="分类名" :label-width="100">
        <el-input v-model="addNoticeform.name" autocomplete="off" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNoticeCateFn"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="name" label="分类名称" width="180" />
    <el-table-column prop="createTime" label="创建时间" width="180" />

    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script setup lang="ts">
import {
  noticeAddRequest,
  noticeDelByIdRequest,
  noticeListRequest,
  type IAddNoticeform,
  type INoticeListItemRes,
} from '@/api/noticeAPI'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

/*
  通知公告添加功能
 */
//控制添加弹框表单的显示和音
const dialogFormVisible = ref(false)
// // interface 限制 添加表单对象的类型(请求体的类型)
// interface IAddNoticeform {
//   name: string
// }
// 添加表单的数据--
const addNoticeform = reactive<IAddNoticeform>({
  name: '',
})

//保存通知公告分类处理函数
async function saveNoticeCateFn() {
  const res = await noticeAddRequest(addNoticeform)
  console.log(res.data)
  if (res.data.code == '200') {
    // 发布成功--隐藏弹框
    dialogFormVisible.value = false
    addNoticeform.name = ''
    // 刷新列表
    loadList()
  }
}

const tableData = ref<INoticeListItemRes[]>([])
//加载分类类别
async function loadList() {
  const res = await noticeListRequest(1, 10)
  console.log(res.data)
  tableData.value = res.data.data.list
}

loadList()

function handleEdit(item: INoticeListItemRes) {
  console.log('edit', item.categoryId)
}
async function handleDelete(item: INoticeListItemRes) {
  ElMessageBox.confirm('确定要删除吗', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(async () => {
      console.log('delete')
      const res = await noticeDelByIdRequest(item._id)
      console.log(res.data)

      if (res.data.code == '200') {
        loadList()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch(() => {})
}
</script>
<style lang="css" scoped></style>
